﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using Newtonsoft.Json;
using System.Web.Mvc;
using WxPayAPI;

namespace WxHelper.Wx
{
    public class WxHelper
    {

        static string tabLog = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;

        #region 获取新的Access_Token
        public static Access_token GetAccess_token()
        {
            string appid = WxPayConfig.APPID;// System.Configuration.ConfigurationManager.AppSettings["WxAppID"].ToString();
            string secret = WxPayConfig.APPSECRET;// System.Configuration.ConfigurationManager.AppSettings["Secret"].ToString();
            string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            string html = HtmlHelper.GetHtml(strUrl, Encoding.UTF8);
            CommonJsonModel model = new CommonJsonModel(html);
            string access_token = model.GetValue("access_token");
            string expires_in = model.GetValue("expires_in");
            Access_token mode = new Access_token();
            mode.access_token = access_token;
            mode.expires_in = expires_in;
            return mode;
        }
        #endregion


        #region 下载多媒体文件

        /// <summary>
        /// 通过Media_ID获取下载微信多媒体文件
        /// </summary>
        /// <param name="MEDIA_ID">文件ID</param>
        /// <returns></returns>
        public static string GetMedia(string media_id)
        {
            string urlpath = "";
            System.Net.HttpWebRequest httpWebRequest = null;
            try
            {
                string ACCESS_TOKEN = IsExistAccess_Token();
                string downLoadUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + ACCESS_TOKEN + "&media_id=" + media_id;

                //根据url获取远程文件流
                httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downLoadUrl);

                System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                string Headers = httpWebResponse.Headers.ToString();
                string filename = httpWebResponse.Headers.Get("Content-disposition").Replace("attachment; filename=\"", "").Replace("\"", "");
                string filepath = AppDomain.CurrentDomain.BaseDirectory + "file\\image\\" + DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                filepath += "\\" + filename;
                urlpath = "file/image/" + DateTime.Now.ToString("yyyyMMdd") + "/" + filename;

                System.IO.Stream sr = httpWebResponse.GetResponseStream();
                //创建本地文件写入流
                System.IO.Stream sw = new System.IO.FileStream(filepath, System.IO.FileMode.Create);

                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = sr.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    sw.Write(by, 0, osize);
                    osize = sr.Read(by, 0, (int)by.Length);
                }
                System.Threading.Thread.Sleep(100);
                sw.Close();
                sr.Close();
                
            }
            catch (System.Exception)
            {
                if (httpWebRequest != null)
                    httpWebRequest.Abort();
            }
            return urlpath;
        }

        #endregion

        #region 根据微信回调的的code获取微信用户的openid、access token信息

        /// <summary>
        /// 根据微信回调的code获取微信用户的openid、access token信息
        /// </summary>
        /// <param name="postdata"></param>
        /// <returns></returns>
        public static Access_token GetOpenID(string code)
        {
             string appid = WxPayConfig.APPID;
             string secret = WxPayConfig.APPSECRET;
            string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
            string html = HtmlHelper.GetHtml(url);
            CommonJsonModel model = new CommonJsonModel(html);
            string OpenID = model.GetValue("openid");
            Access_token mode = new Access_token();
            mode.access_token = model.GetValue("access_token");
            mode.expires_in = model.GetValue("expires_in");
            mode.Refresh_token = model.GetValue("refresh_token");
            mode.OpenId = model.GetValue("openid");
            mode.Scope = model.GetValue("scope");
            return mode;
        }

        #endregion

        #region 根据当前日期 判断Access_Token 是否超期  如果超期返回新的Access_Token   否则返回之前的Access_Token
        public static string IsExistAccess_Token()
        {
            string Token = string.Empty;
            DateTime YouXRQ;
            // 读取XML文件中的数据，并显示出来 ，注意文件路径 
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "Configs/XMLFile.xml";
            StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8);
            XmlDocument xml = new XmlDocument();
            xml.Load(str);
            str.Close();
            str.Dispose();
            Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText;
            YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText);
            if (DateTime.Now > YouXRQ)
            {
                DateTime _youxrq = DateTime.Now;
                Access_token mode = GetAccess_token();
                xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token;
                _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in));
                xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString();
                xml.Save(filepath);
                Token = mode.access_token;
            }
            return Token;
        }
        #endregion

        #region 获取新的jsapi_ticket
        public static Access_token GetJsapi_ticket()
        {
            string ACCESS_TOKE = IsExistAccess_Token();
            //string strUrl = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + ACCESS_TOKE;
            string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + ACCESS_TOKE + "&type=jsapi";
            string html = HtmlHelper.GetHtml(url, Encoding.UTF8);
            CommonJsonModel model = new CommonJsonModel(html);
            string ticket = model.GetValue("ticket");
            string expires_in = model.GetValue("expires_in");
            Access_token mode = new Access_token();
            mode.access_token = ticket;
            mode.expires_in = expires_in;
            return mode;
        }
        #endregion

        #region 根据当前日期 变得jsapi 是否超期
        public static string IsExistJsapi_ticket()
        {
            string Token = string.Empty;
            DateTime YouXRQ;
            // 读取XML文件中的数据，并显示出来 ，注意文件路径 
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "Configs/XMLFile.xml";
            StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8);
            XmlDocument xml = new XmlDocument();
            xml.Load(str);
            str.Close();
            str.Dispose();
            Token = xml.SelectSingleNode("xml").SelectSingleNode("jsapi_ticket").InnerText;
            YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("jsapi_YouXRQ").InnerText);
            if (DateTime.Now > YouXRQ)
            {
                DateTime _youxrq = DateTime.Now;
                Access_token mode = GetJsapi_ticket();
                xml.SelectSingleNode("xml").SelectSingleNode("jsapi_ticket").InnerText = mode.access_token;
                _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in));
                xml.SelectSingleNode("xml").SelectSingleNode("jsapi_YouXRQ").InnerText = _youxrq.ToString();
                xml.Save(filepath);
                Token = mode.access_token;
            }
            return Token;
        }
        #endregion

        #region 微信url编码(用于回调)

        /// <summary>
        /// 微信url编码(用于回调)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string WXUrlEncode(string url)
        {
            url = HtmlHelper.UrlEncode(url);
            string appid = WxPayConfig.APPID;
            string WxUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

            return (WxUrl);
        }

        #endregion

        /// <summary>
        /// SHA1哈希加密算法
        /// </summary>
        /// <param name="str_sha1_in"></param>
        /// <returns></returns>
        public static string SHA1_Hash(string str_sha1_in)
        {
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
            str_sha1_out = str_sha1_out.Replace("-", "").ToLower();
            return str_sha1_out;
        }
    }
}
